<template>
    <el-dialog @open="open" v-model="props.isOpen" title="配置角色菜单" @close="close" style="width: 30%">
        <el-tree
                ref="treeRef"
                :data="treeData"
                show-checkbox
                default-expand-all
                node-key="id"
                highlight-current
                :props="defaultProps"
                :render-content="renderContent"
        />
        <div class="buttons" style="display: flex;align-items:center;justify-content:center;">
            <el-button type="primary" activity @click="saveMenusForRole">保存</el-button>
            <el-button type="primary" activity @click="close">取消</el-button>
        </div>
    </el-dialog>
</template>

<script setup>
    import {ref,reactive,nextTick,onUpdated,onMounted} from 'vue'
    import request from '@/utils/request.js'
    import { ElMessage } from 'element-plus'
    const treeRef = ref(null)
    let props = defineProps(['id','isOpen'])
    let emits = defineEmits(['close'])

    const defaultProps = {
        children: 'children',
        label: 'name',
    }
    let treeData = reactive([])

    onMounted(function () {
        request.get(`/api/menu/getMenusWithLevel`).then(resp => {
            treeData.push(...resp)
            treeData.value = resp
        })
    })

    function open() {
        if(props.isOpen === true){
            request.get(`/api/menu/getMenusForRole/${props.id}`).then(resp => {
            treeRef.value.setCheckedKeys(resp, false)
            })
        }
    }

    function close(){
        emits('close')
    }

    function saveMenusForRole(){
        //获取所有被勾选的节点,不要半勾选的节点
        let nodes = treeRef.value.getCheckedNodes(false, false)

        let menus = []
        selectInnerIds(nodes, menus)

        let menusForRole = {roleId:props.id, menus:menus}
        request.post("/api/menu/saveMenusForRole", menusForRole).then(resp => {
            success()
        })
    }

    function selectInnerIds(nodes, menus) {
        nodes.forEach(n=>{
            if(n.children.length===0){
                menus.push({id:n.id, parentFullId: n.parentFullId})
            }else{
                selectInnerIds(n.children, menus)
            }
        })
    }

    function success(){
        ElMessage({message: '修改成功！',type: 'success'})
        emits('close')
    }

    function renderContent(h, nodeInfo){
        let data = nodeInfo.node.data
        if(data.level===1){
            return h('label', {style:'padding:1px 5px;background:#E6A23C;color:white;border-radius:5px'}, data.name)
        }else if(data.level===2){
            return h('label', {style:'padding:1px 5px;background:#409EFF;color:white;border-radius:5px'}, data.name)
        }else if(data.level===3){
            return h('label', {style:'padding:1px 5px;background:#67C26D;color:white;border-radius:5px'}, data.name)
        }
    }

</script>

<style scoped>
</style>